package com.llt.chatroom.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.llt.chatroom.component.OnlineUserManager;
import com.llt.chatroom.mapper.SessionMapper;
import com.llt.chatroom.model.Friend;
import com.llt.chatroom.model.Message;
import com.llt.chatroom.model.User;
import com.llt.chatroom.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class WebSocketController extends TextWebSocketHandler {

    @Resource
    private OnlineUserManager onlineUserManager;

    @Resource
    private SessionMapper sessionMapper;

    @Resource
    private MessageService messageService;

    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 会在建立连接成功够后，自动调用
        log.info("websocket连接成功");

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }
        log.info("获取到的 userid: " + user.getUserId());

        // 上线
        onlineUserManager.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // webSocket收到消息的时候自动调用
        log.info("收到消息: " + message.toString());

        // session 中记录了通信双方是谁
        session.sendMessage(message);

        // 1.获取到当前用户信息
        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            log.error("user == null");
            return;
        }

        // 2. 针对请求进行解析, 转 json 为 java 对象
        MessageRequest req = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if (req.getType().equals("message")) {
            // 进行消息转发
            transferMessage(user, req);
        }else {
            log.error("type 有误" + message.getPayload());
        }
        
    }

    private void transferMessage(User fromUser, MessageRequest req) throws IOException {
        // 1. 构造待转发的响应对象
        MessageResponse resp = new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getUserId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());

        String respJson = objectMapper.writeValueAsString(resp);

        // 2. 根据 sessionId 获取到都有哪些用户
        List<Friend> friends = sessionMapper.getFriendsBySessionId(req.getSessionId(), fromUser.getUserId());
        Friend myself = new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);

        // 3. 遍历这个列表，给每一个用户发一份 (也得给自己发)
        for (Friend friend : friends) {
            WebSocketSession webSocketSession = onlineUserManager.getSession(friend.getFriendId());
            if (webSocketSession == null) {
                // 用户不在线就不发
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respJson));
        }

        // 4. 发的数据放到数据库里
        Message message = new Message();
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());

        messageService.add(message);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 连接出现异常时自动调用
        log.error("websocket连接异常: " + exception.toString());

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        // 下线
        onlineUserManager.offline(user.getUserId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 正常关闭后自动调用
        log.info("websocket连接关闭: " + status.toString());

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        // 下线
        onlineUserManager.offline(user.getUserId(), session);
    }
}
